package com.msx.trade.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.msx.credit.service.Orderservice;
import com.msx.pojo.*;
import com.msx.trade.mapper.*;
import com.msx.trade.utils.HttpClientUtils;
import com.msx.trade.utils.MD5Sign;
import com.msx.user.service.IdentityServiceInterface;
import com.msx.user.service.TiedcardServiceInterface;
import com.msx.util.ResponseResult;
import com.msx.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;


@Service
public class Huankuanserviceimpl{
    private String merId;


    private String appSercret;
    @Autowired
    private BillOrderMapper billOrderMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BizBankMapper bizBankMapper;
    @Autowired
    private SmsMapper smsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RepaymentOrderMapper repaymentOrderMapper;
   @Autowired
   private OrderMapper orderMapper;
    @Reference(version = "2.0.0")
    private TiedcardServiceInterface tiedcardServiceInterface;
    @Reference(version = "2.0.0")
    private IdentityServiceInterface identityServiceInterface;



    /**
     * 查询当前期数
     * @param qishu
     * @return
     */
    public ResponseResult huankuan(String bid) {
        BillOrder billOrder = billOrderMapper.selectQishu(bid);



        return new ResponseResult(StatusCode.OK,"成功",billOrder);

    }

    /**
     * 账单列表
     * @return
     */
    public ResponseResult zhuangdan(){


        List<BillOrder> billOrders = billOrderMapper.selectfindAll(1);
        return new ResponseResult(StatusCode.OK,"成功",billOrders);

    }

    /** 带用第三方接口 银行验证发送验证码
     *
     */

    public ResponseResult hkyzm(HttpServletRequest request){
        String uuid = request.getHeader("uuid");
        Integer user = (Integer)redisTemplate.opsForValue().get(uuid);

        User user1 = userMapper.selectByPrimaryKey(user);
        Integer userid = user1.getId();
        Order order=orderMapper.uidservice(userid);
        Tiedcard selecttidecard = tiedcardServiceInterface.findByIduserid(userid);
        Identity selectidentity = identityServiceInterface.selectidentity(userid);
        Integer bankId = selecttidecard.getBankId();
        BizBank selectbankshort = bizBankMapper.selectByPrimaryKey(bankId);
        String hk = this.hkrz("张三", selectidentity.getIdentityCode(), selecttidecard.getBankCode(), selectbankshort.getBankName(), selectbankshort.getBankShortName(), order.getId(), order.getBorrowMoney());
        JSONObject jsonObject = JSON.parseObject(hk);
        JSONObject code = jsonObject.getJSONObject("data");
        String code1 = code.getString("code");
        redisTemplate.opsForValue().set("code1",code1);
        Sms sms = new Sms();
        sms.setMobile("111111");
        sms.setContent("006463");
        sms.setSendTime(new Date());
        sms.setSmsType("调用还款银行卡认证接口");
        sms.setUserId(1);
        sms.setIsDelete("0");
        smsMapper.insert(sms);
        return new ResponseResult(StatusCode.OK,code1);



    }
    public ResponseResult hkjk(HttpServletRequest request,String yzm,String bid){
              String uuid = request.getHeader("uuid");
        Integer user1 = (Integer)redisTemplate.opsForValue().get(uuid);

        User user = userMapper.selectByPrimaryKey(user1);
        Integer userid = user.getId();


        if(!yzm.equals("123")){
            return new ResponseResult(StatusCode.ERROR,"失败");
        }


        Order order=orderMapper.uidservice(userid);
        Tiedcard selecttidecard = tiedcardServiceInterface.findByIduserid(userid);
        Identity selectidentity = identityServiceInterface.selectidentity(userid);
        BillOrder billOrder = billOrderMapper.selectQishu(bid);
        Integer bankId = selecttidecard.getBankId();
        BizBank selectbankshort = bizBankMapper.selectbankshort(bankId);
        //添加还款记录
        RepaymentOrder repaymentOrder = new RepaymentOrder();
        repaymentOrder.setOrderId(order.getId());
        repaymentOrder.setTransactionId(bid);
        repaymentOrder.setUserName(user.getUserName());
        repaymentOrder.setBankName(selectbankshort.getBankName());
        repaymentOrder.setBankCode(selecttidecard.getBankCode());
        repaymentOrder.setBankShort(selectbankshort.getBankShortName());
        repaymentOrder.setIdentityCode(selectidentity.getIdentityCode());
        repaymentOrder.setLoanTime(new Date());
        repaymentOrder.setRefundMoney(billOrder.getWhichMoney());
        repaymentOrder.setUserId(user.getId());
        repaymentOrder.setIsDelete("0");
        repaymentOrderMapper.insert(repaymentOrder);
        //调用第三方还款接口
        String ss = this.hk(user.getUserName(), selectidentity.getIdentityCode(), selecttidecard.getBankCode(), selectbankshort.getBankName(), selectbankshort.getBankShortName(), order.getId(), order.getBorrowMoney());
        JSONObject jsonObject = JSON.parseObject(ss);
        JSONObject data = jsonObject.getJSONObject("data");
        String thirdTradeNo = (String) data.get("thirdTradeNo");

        RepaymentOrder repaymentOrder1 = repaymentOrderMapper.selectRepay(userid);

        repaymentOrder1.setOutTradeNo(thirdTradeNo);
        repaymentOrder1.setTradeState("0");
        repaymentOrderMapper.updateByPrimaryKeySelective(repaymentOrder1);

        return new ResponseResult(StatusCode.OK,"成功");

    }
    @Scheduled(cron = "0 0 1 * * ?")
    public ResponseResult renzj(){
        List<RepaymentOrder> selectstart = repaymentOrderMapper.selectAll();
        for(RepaymentOrder a:selectstart){
            String tradeState = a.getTradeState();
            if(tradeState.equals("0")){
                String orderId = a.getOrderId();
                RepaymentOrder selectorder = repaymentOrderMapper.selectorder(orderId);
                String outTradeNo = selectorder.getOutTradeNo();
                String fangkuanrenzheng = this.fangkuanrenzheng(outTradeNo);
                JSONObject jsonObject = JSON.parseObject(fangkuanrenzheng);
                JSONObject data = jsonObject.getJSONObject("data");
                String msgCode = (String) data.get("msgCode");
               if(!msgCode.equals("E200")){
                   selectorder.setTradeState("2");
                   repaymentOrderMapper.updateByPrimaryKeySelective(selectorder);
                   return new ResponseResult(StatusCode.ERROR,"失败");
               }
                selectorder.setTradeState("1");

                repaymentOrderMapper.updateByPrimaryKeySelective(selectorder);
                String transactionId = a.getTransactionId();

                BillOrder billOrder = billOrderMapper.selectQishu(transactionId);

                billOrder.setState("1");
                billOrderMapper.updateByPrimaryKeySelective(billOrder);
                return new ResponseResult(StatusCode.OK,"成功");

            }
        }

        return new ResponseResult(StatusCode.ERROR,"失败");
    }



    /**
     * 还款验证码第三方接口
     * @param name
     * @param cardId
     * @param accNo
     * @param bankName
     * @param bankShortName
     * @param merTradeNo
     * @param amount
     * @return
     */
    public String hkrz(String name, String cardId, String accNo, String bankName, String bankShortName, String merTradeNo, BigDecimal amount) {
        String url="http://10.1.74.19:8080/api/common/collectionSms";
        Map<String,String> mapa = new HashMap<>();
        mapa.put("merId",merId);
        mapa.put("name",name);
        mapa.put("cardId",cardId);
        mapa.put("accNo",accNo);
        mapa.put("bankName",bankName);
        mapa.put("bankShortName",bankShortName);
        mapa.put("merTradeNo",merTradeNo);
        mapa.put("amount",amount+"");
        String sign = MD5Sign.sign(mapa,appSercret);
        mapa.put("sign",sign);
        String strr = HttpClientUtils.httpPost(url,mapa);
        return strr;
    }

    /**
     * 还款碲酸放接口
     * @param name
     * @param cardId
     * @param accNo
     * @param bankName
     * @param bankShortName
     * @param merTradeNo
     * @param amount
     * @return
     */
    public String hk(String name, String cardId, String accNo, String bankName, String bankShortName, String merTradeNo, BigDecimal amount) {
        String url="http://10.1.74.19:8080/api/common/collectionConfirm";
        Map<String,String> mapa = new HashMap<>();
        mapa.put("merId",merId);
        mapa.put("name",name);
        mapa.put("cardId",cardId);
        mapa.put("accNo",accNo);
        mapa.put("bankName",bankName);
        mapa.put("bankShortName",bankShortName);
        mapa.put("merTradeNo",merTradeNo);
        mapa.put("amount",amount+"");
        String sign = MD5Sign.sign(mapa,appSercret);
        mapa.put("sign",sign);
        String strr = HttpClientUtils.httpPost(url,mapa);
        return strr;
    }
    /**
     * 放款认证接口
     * @param thirdTradeNo
     * @return
     */

    public String fangkuanrenzheng(String thirdTradeNo) {
        String url="http://10.1.74.19:8080/api/common/queryTradeResult";
        Map<String,String> map = new HashMap<>();
        map.put("merId",merId);
        map.put("thirdTradeNo",thirdTradeNo);
        String sign = MD5Sign.sign(map,appSercret);
        map.put("sign",sign);
        String str = HttpClientUtils.httpPost(url,map);
        return str;
    }



}
